/*
 * @Author: your name
 * @Date: 2021-06-17 10:57:57
 * @LastEditTime: 2021-06-17 15:26:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \consumeTask\market\coupon.go
 */
package main

import (
	"context"
	"encoding/json"
	"git.900sui.cn/kc/base/utils"
	"git.900sui.cn/kc/kcgin"
	"git.900sui.cn/kc/rabbitmq"
	"git.900sui.cn/kc/rpcinterface/client/market"
	msg2 "git.900sui.cn/kc/rpcinterface/client/msg"
	m2 "git.900sui.cn/kc/rpcinterface/interface/market"
	msg3 "git.900sui.cn/kc/rpcinterface/interface/msg"
	tasks "git.900sui.cn/kc/rpcinterface/interface/task/market"
	"github.com/streadway/amqp"
	"log"
	"strconv"
)

func main() {
	err := consumeMQHandle()
	if err != nil {
		utils.Logerr.Printf("优惠券推送错误, err:%s", err)
	}
}

func getReceiveCouponOfUser(cId int) (result []m2.ReceiveCouponUserListByIdReply, err error) {
	client := new(market.Coupon).Init()
	args := &m2.ReceiveCouponUserListByIdArgs{
		CouponId: cId,
	}
	if err = client.GetReceivedCouponUserListById(context.Background(), args, &result); err != nil {
		return
	}
	return
}

func consumeMQHandle() (err error) {
	err = rabbitmq.Rabbitmq.Consume(kcgin.AppConfig.String("market.queue.setCoupon"), func(msg amqp.Delivery) {
		var args tasks.ArgsCouponProduce
		err = json.Unmarshal(msg.Body, &args)
		if err != nil {
			log.Fatalf("%v", err)
			return
		}
		userCouponList, err := getReceiveCouponOfUser(args.CouponId)
		if err != nil {
			log.Fatalf("%v", err)
			return
		}
		if len(userCouponList) == 0 {
			log.Println("用户尚未领取该优惠券")
			return
		}

		//获取该优惠券的信息
		couponClient:=new(market.Coupon).Init()
		couponArgs:=&m2.GetCouponInfoArgs{
			BsId: args.BusId,
			Id:args.CouponId,
		}
		couponRep:=new(m2.CouponReply)
		if err:=couponClient.FindCouponByIdOfInternal(context.Background(),couponArgs,couponRep);err !=nil{
			return
		}

		client:=new(msg2.Msg).Init()
		for _,val:=range userCouponList{
			go func(uid int){
				msgArgs:=&msg3.PushSystemMsgArgs{
					Source: msg3.MSG_SOURCE_1,
					BsId: args.BusId,
					Title: couponRep.Name,
					Time: strconv.Itoa(couponRep.NoticeExpire),
					Uid: uid,
				}
				var msgReply bool
				if err=client.PushSystemMsg(context.Background(),msgArgs,&msgReply);err !=nil{
					return
				}
			}(val.Uid)
		}
	})
	return
}



